#import "ImageViewController.h"
#import "ImageCell.h"
#import <Foundation/Foundation.h>

@interface ImageViewController () <NSURLSessionDelegate, UITableViewDataSource>

@property (strong, nonatomic) NSArray<NSString *> * imgURL;
//@property (strong,nonatomic) NSMutableArray * dataSource;
@property (strong,nonatomic) UITableView * tableView;
@property (strong,nonatomic) UIActivityIndicatorView * load; // 加载动画

//@interface ImageViewController ()<UITableViewDataSource,UITableViewDelegate> {
//    NSMutableArray<NSURL *> * urlList;
//}
//@property (strong,nonatomic) UITableView * tableView;

@end

@implementation ImageViewController

//- (NSMutableArray *)dataSource {
//    if (_dataSource == nil) {
//        _dataSource = [NSMutableArray array];
//    }
//    return _dataSource;
//}
//
//- (instancetype)init{
//   self = [super init];
//    self.tabBarItem.title = @"图片";
//    NSURL * url1 = [NSURL URLWithString:@"https://hbimg.huabanimg.com/d8784bbeac692c01b36c0d4ff0e072027bb3209b106138-hwjOwX_fw658"];
//    NSURL * url2 = [NSURL URLWithString:@"https://hbimg.huabanimg.com/6215ba6f9b4d53d567795be94a90289c0151ce73400a7-V2tZw8_fw658"];
//    NSURL * url3 = [NSURL URLWithString:@"https://hbimg.huabanimg.com/834ccefee93d52a3a2694535d6aadc4bfba110cb55657-mDbhv8_fw658"];
//    NSURL * url4 = [NSURL URLWithString:@"https://hbimg.huabanimg.com/f3085171af2a2993a446fe9c2339f6b2b89bc45f4e79d-LacPMl_fw658"];
//    NSURL * url5 = [NSURL URLWithString:@"https://hbimg.huabanimg.com/e5c11e316e90656dd3164cb97de6f1840bdcc2671bdc4-vwCOou_fw658"];
//    self->urlList = [NSMutableArray arrayWithObjects: url1, url2, url3, url4, url5];
//    return self;
//}
//
//- (void)viewDidLoad {
//    [super viewDidLoad];
//    [super viewDidLoad];
//    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
//    layout.scrollDirection = UICollectionViewScrollDirectionVertical;//UICollectionViewScrollDirectionVertical;
//    layout.itemSize = CGSizeMake(self.view.frame.size.width - 10, 170);
//    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
//    tableView.dataSource = self;
//    tableView.delegate = self;
//
//        // 设置行高
//    tableView.rowHeight = 200;
//
//        // 去掉分割线
//    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
//
//        // 设置背景色
//    tableView.backgroundColor = [UIColor blackColor];
//
//        // 取消点击
//    tableView.allowsSelection = NO;
//    self.tableView = tableView;
//
//        // cell注册
//    [tableView registerClass:[ImageCell class] forCellReuseIdentifier:@"cell"];
//
//    [self.view addSubview:tableView];
//    [self createButton];
//}
//
//- (void)createButton {
//    UIButton *btn1, *btn2, *btn3;
//
//    btn1 = [[UIButton alloc] init];
//    btn2 = [[UIButton alloc] init];
//    btn3 = [[UIButton alloc] init];
//
//    btn1 = [UIButton buttonWithType:UIButtonTypeSystem];
//    btn2 = [UIButton buttonWithType:UIButtonTypeSystem];
//    btn3 = [UIButton buttonWithType:UIButtonTypeSystem];
//
//    [btn1 setTitle:@"加载" forState:UIControlStateNormal];
//    [btn2 setTitle:@"清空" forState:UIControlStateNormal];
//    [btn3 setTitle:@"删除缓存" forState:UIControlStateNormal];
//
//    btn1.frame = CGRectMake((self.view.bounds.size.width - 240) / 4, self.view.bounds.size.height - 170, 80, 40);
//    btn1.layer.cornerRadius = 10.0;
//    btn1.backgroundColor = [UIColor whiteColor];
//    btn1.layer.borderColor = [UIColor grayColor].CGColor;
//    btn1.layer.borderWidth = 1.0;
//    btn1.layer.shadowColor = [UIColor blackColor].CGColor;
//    btn1.layer.shadowOffset = CGSizeMake(5, 5);
//    btn1.layer.shadowRadius = 5;
//    btn1.layer.shadowOpacity = 0.5;
//
//    btn2.frame = CGRectMake((self.view.bounds.size.width - 240) / 4 * 2 + 80, self.view.bounds.size.height - 170, 80, 40);
//    btn2.layer.cornerRadius = 10.0;
//    btn2.backgroundColor = [UIColor whiteColor];
//    btn2.layer.borderColor = [UIColor grayColor].CGColor;
//    btn2.layer.borderWidth = 1.0;
//    btn2.layer.shadowColor = [UIColor blackColor].CGColor;
//    btn2.layer.shadowOffset = CGSizeMake(5, 5);
//    btn2.layer.shadowRadius = 5;
//    btn2.layer.shadowOpacity = 0.5;
//
//    btn3.frame = CGRectMake((self.view.bounds.size.width - 240) / 4 * 3 + 160, self.view.bounds.size.height - 170, 80, 40);
//    btn3.layer.cornerRadius = 10.0;
//    btn3.backgroundColor = [UIColor whiteColor];
//    btn3.layer.borderColor = [UIColor grayColor].CGColor;
//    btn3.layer.borderWidth = 1.0;
//    btn3.layer.shadowColor = [UIColor blackColor].CGColor;
//    btn3.layer.shadowOffset = CGSizeMake(5, 5);
//    btn3.layer.shadowRadius = 5;
//    btn3.layer.shadowOpacity = 0.5;
//
//    [btn1 addTarget:self action:@selector(downloadIMG:) forControlEvents:UIControlEventTouchUpInside];
//    [btn2 addTarget:self action:@selector(cleanIMG:) forControlEvents:UIControlEventTouchUpInside];
//    [btn3 addTarget:self action:@selector(cleanCache:) forControlEvents:UIControlEventTouchUpInside];
//
//    [self.view addSubview:btn1];
//    [self.view addSubview:btn2];
//    [self.view addSubview:btn3];
//}
//
//-(void)downloadIMG:(UIButton*)btn{
//    NSMutableArray<NSData *> * imageSet = [NSMutableArray arrayWithCapacity:5];
//
//    // If the cache is not empty, then read data from cache directly.
//    if ([self isCacheExist]) {
//        NSLog(@"Cache is not empty!");
//        NSString * cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//
//        for (int i = 0; i < [self->urlList count]; i++) {
//            NSString * filePath = [cacheDir stringByAppendingPathComponent:[@"image" stringByAppendingString:[NSString stringWithFormat:@"%d", i]]];
//            NSData * data = [NSData dataWithContentsOfFile:filePath];
//            imageSet[i] = data;
//        }
//
//        NSMutableArray<UIImage *> * newImageSet = [NSMutableArray arrayWithCapacity:5];
//        for (int i = 0; i < [self->urlList count]; i++) {
//            newImageSet[i] = [UIImage imageWithData:imageSet[i]];
//        }
//
//        for (int i = 0; i < [self->urlList count]; i++) {
//            self.dataSource[i] = newImageSet[i];
//        }
//        [self.tableView reloadData];
//    }
//
//    // Else load data from network throught multithread.
//    else {
//        NSLog(@"Cache is empty!");
//        [self.tableView reloadData];
//        dispatch_queue_t downloadQueue = dispatch_queue_create("download.images", NULL);
//        for (int i = 0; i < [self->urlList count]; i++) {
//            dispatch_async(downloadQueue, ^{
//                // Write data into the cache.
//                NSString * cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//                imageSet[i] = [NSData dataWithContentsOfURL:self->urlList[i]];
//                NSString * filePath = [cacheDir stringByAppendingPathComponent:[@"image" stringByAppendingString:[NSString stringWithFormat:@"%d", i]]];
//                [imageSet[i] writeToFile:filePath atomically:YES];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    // [NSThread sleepForTimeInterval:0.5];
//                    self.dataSource[i] = [UIImage imageWithData:imageSet[i]];
//                    [self.tableView reloadData];
//                });
//            });
//        }
//    }
//
//}
//
//- (BOOL)isCacheExist {
//    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString * path = [paths objectAtIndex:0];
//    NSString * filePath = [path stringByAppendingPathComponent:@"image0"];
//    NSFileManager * fileManager = [NSFileManager defaultManager];
//    BOOL result = [fileManager fileExistsAtPath:filePath];
//    NSLog(@"这个文件已经存在：%@",result?@"是的":@"不存在");
//    return result;
//}
//
//- (void)cleanIMG:(UIButton*)btn{
//    [self.dataSource removeAllObjects];
//    [self.tableView reloadData];
//}
//
//- (void)cleanCache:(UIButton*)btn{
//    NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
//    NSArray * files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
//    for (NSString * p in files) {
//        NSError * error = nil;
//        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent:p];
//        if ([[NSFileManager defaultManager] fileExistsAtPath:fileAbsolutePath]) {
//            [[NSFileManager defaultManager] removeItemAtPath:fileAbsolutePath error:&error];
//        }
//    }
//}
//
//// 返回每个section的item数
//- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
//    return 1;
//}
//- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    return [self.dataSource count];
//}
//
//// 设置cell
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {
//    ImageCell *cell = (ImageCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
//    cell.imgView.image = _dataSource[indexPath.row];
//    return cell;
//}
//
//// 设置cell的间距
//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
//    // UIEdgeInsets insets = {top, left, bottom, right};
//    return UIEdgeInsetsMake(10, 25, 10, 25);
//}

// 构建页面
- (instancetype) init {
    if (self = [super init]){
        self.view.backgroundColor = [UIColor whiteColor];
        self.navigationItem.title = @"图片浏览";
        [self setTabBar];
        [self setImgURL];
        [self setTableView];
        [self createButton];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}

// 设置底部tabbar样式
- (void)setTabBar {
    self.tabBarItem.title = @"浏览";
    UIImage *img1 = [[UIImage imageNamed:@"mine.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIImage *img2 = [[UIImage imageNamed:@"mine2.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.tabBarItem.image = img1; self.tabBarItem.selectedImage = img2;
    [self.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} forState:UIControlStateSelected];
}

// 设置三个按钮
- (void)createButton {
    UIButton *btn1, *btn2, *btn3;

    btn1 = [[UIButton alloc] init];
    btn2 = [[UIButton alloc] init];
    btn3 = [[UIButton alloc] init];

    btn1 = [UIButton buttonWithType:UIButtonTypeSystem];
    btn2 = [UIButton buttonWithType:UIButtonTypeSystem];
    btn3 = [UIButton buttonWithType:UIButtonTypeSystem];

    [btn1 setTitle:@"加载" forState:UIControlStateNormal];
    [btn2 setTitle:@"清空" forState:UIControlStateNormal];
    [btn3 setTitle:@"删除缓存" forState:UIControlStateNormal];

    btn1.frame = CGRectMake((self.view.bounds.size.width - 240) / 4, self.view.bounds.size.height - 170, 80, 40);
    btn1.layer.cornerRadius = 10.0;
    btn1.backgroundColor = [UIColor whiteColor];
    btn1.layer.borderColor = [UIColor grayColor].CGColor;
    btn1.layer.borderWidth = 1.0;
    btn1.layer.shadowColor = [UIColor blackColor].CGColor;
    btn1.layer.shadowOffset = CGSizeMake(5, 5);
    btn1.layer.shadowRadius = 5;
    btn1.layer.shadowOpacity = 0.5;

    btn2.frame = CGRectMake((self.view.bounds.size.width - 240) / 4 * 2 + 80, self.view.bounds.size.height - 170, 80, 40);
    btn2.layer.cornerRadius = 10.0;
    btn2.backgroundColor = [UIColor whiteColor];
    btn2.layer.borderColor = [UIColor grayColor].CGColor;
    btn2.layer.borderWidth = 1.0;
    btn2.layer.shadowColor = [UIColor blackColor].CGColor;
    btn2.layer.shadowOffset = CGSizeMake(5, 5);
    btn2.layer.shadowRadius = 5;
    btn2.layer.shadowOpacity = 0.5;

    btn3.frame = CGRectMake((self.view.bounds.size.width - 240) / 4 * 3 + 160, self.view.bounds.size.height - 170, 80, 40);
    btn3.layer.cornerRadius = 10.0;
    btn3.backgroundColor = [UIColor whiteColor];
    btn3.layer.borderColor = [UIColor grayColor].CGColor;
    btn3.layer.borderWidth = 1.0;
    btn3.layer.shadowColor = [UIColor blackColor].CGColor;
    btn3.layer.shadowOffset = CGSizeMake(5, 5);
    btn3.layer.shadowRadius = 5;
    btn3.layer.shadowOpacity = 0.5;

    [btn1 addTarget:self action:@selector(loadIMG:) forControlEvents:UIControlEventTouchUpInside];
    [btn2 addTarget:self action:@selector(clearIMG:) forControlEvents:UIControlEventTouchUpInside];
    [btn3 addTarget:self action:@selector(clearCache:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:btn1];
    [self.view addSubview:btn2];
    [self.view addSubview:btn3];
}

//// 设置TableView
//-(void)setTableView{
//    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
//
//    tableView.dataSource = self;
//
//    // 设置行高
//    tableView.rowHeight = 200;
//
//    // 去掉分割线
//    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
//
//    // 设置背景色
//    tableView.backgroundColor = [UIColor blackColor];
//
//    // 取消点击
//    tableView.allowsSelection = NO;
//    self.tableView = tableView;
//
//    // cell注册
//    [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"cell"];
//
//    [self.view addSubview:self.tableView];
//}

// 设置TableView
-(void)setTableView{
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    tableView.dataSource = self;
//    tableView.delegate = self;

    // 设置行高
    tableView.rowHeight = 200;

    // 去掉分割线
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];

    // 设置背景色
    tableView.backgroundColor = [UIColor blackColor];

    // 取消点击
    tableView.allowsSelection = NO;
    self.tableView = tableView;

    // cell注册
    [tableView registerClass:[ImageCell class] forCellReuseIdentifier:@"cell"];

    [self.view addSubview:tableView];
}

// 设置图片的URL地址
- (void)setImgURL{
    NSString *img1 = @"https://hbimg.huabanimg.com/d8784bbeac692c01b36c0d4ff0e072027bb3209b106138-hwjOwX_fw658";
    NSString *img2 = @"https://hbimg.huabanimg.com/6215ba6f9b4d53d567795be94a90289c0151ce73400a7-V2tZw8_fw658";
    NSString *img3 = @"https://hbimg.huabanimg.com/834ccefee93d52a3a2694535d6aadc4bfba110cb55657-mDbhv8_fw658";
    NSString *img4 = @"https://hbimg.huabanimg.com/f3085171af2a2993a446fe9c2339f6b2b89bc45f4e79d-LacPMl_fw658";
    NSString *img5 = @"https://hbimg.huabanimg.com/e5c11e316e90656dd3164cb97de6f1840bdcc2671bdc4-vwCOou_fw658";
    self.imgURL = [NSArray arrayWithObjects:img1, img2, img3, img4, img5, nil];
}

// 加载图片
- (void)loadIMG:(UIButton *)sender {
    if (_dataSource.count == 0){
        for (int i = 0; i < 5; i++){
            // 在缓存中找这张图片
//            NSLog(@"找图片");
            if ([self findImgFromCacheByIndex:i]){
                [self.dataSource addObject:[self getImgFromCache:i]];
                NSLog(@"找到图片");
            }
            else {
//                [self.dataSource addObject:[UIImage imageNamed:@"load.png"]];
                [self getImgFromURL:i];
//                NSLog(@"没找到");
            }
//            NSLog(@"找完了");
        }
        // 刷新tableview
        [self.tableView reloadData];
    }
}

// 清除图片
- (void)clearIMG:(UIButton *)sender {
    [_dataSource removeAllObjects];
    _dataSource = [[NSMutableArray alloc]initWithCapacity:5];
    [self.tableView reloadData];
}

// 清除缓存
- (void)clearCache:(UIButton *)sender {
    // 获取cache路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];

    // 文件操作
    NSFileManager *fileManager = [NSFileManager defaultManager];
    for (int i = 0; i < 5; i++){
        NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"img%ld.png",(long)i]];
         if ([fileManager fileExistsAtPath:filePath]){
             [fileManager removeItemAtPath:filePath error:nil];
             NSLog(@"图片序号%d \n",i);
         }
     }
 }

// 从网上下载图片
- (void)getImgFromURL:(int)index{
    // 创建并发队列
    dispatch_queue_t queue = dispatch_queue_create("tag", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"创建了并发队列");
    // 创建异步执行任务
    dispatch_async(queue,^{
        NSURL *url = [NSURL URLWithString:self.imgURL[index]];
        NSLog(@"%@", url);
        // 通过对应的URL下载index的图片
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
        NSLog(@"下载成功");
        // 放入datasource，更新UI
        self->_dataSource[index] = image;

        // tableview只能在主线程更新
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];

        // 更新完UI之后，才存入缓存
        [self saveImgToCache:image Index:index];
        NSLog(@"更新了UI");
    });
}

//// 从网上下载图片
//- (void)getImgFromURL:(int)index{
//    // 创建并发队列
//    dispatch_queue_t queue = dispatch_queue_create("tag", DISPATCH_QUEUE_CONCURRENT);
//
//    // 创建异步执行任务
//    dispatch_async(queue,^{
//        NSURL *url = [NSURL URLWithString:self.imgURL[index]];
//        NSLog(@"图片序号%d",index);
//        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//
//        // 放入datasource，更新UI
//
////        self->_dataSource[index] = image;
//        [self->_dataSource addObject:image];
//        [self saveImgToCache:image Index:index];
//
//        // tableview只能在主线程更新
//        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
//
////        // 更新完UI之后，才存入缓存
////        [self saveImgToCache:image Index:index];
//    });
//}


// 保存图片到缓存
- (void)saveImgToCache:(UIImage *)image Index:(NSInteger) index{
    // 获取cache路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];

    // 文件操作
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"img%ld.png",(long)index]];

   if ([fileManager fileExistsAtPath:filePath]){
       NSLog(@"File %@ is already saved.",filePath);
   }else {
       // 创建图片
       [fileManager createFileAtPath:filePath contents:nil attributes:nil];
       [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];
       NSLog(@"保存成功");
    }
}

// 判断编号为i的图片是否在缓存中
- (BOOL)findImgFromCacheByIndex:(NSInteger) index{
    // 获取cache路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];

    // 文件操作
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"img%ld.png",(long)index]];

    NSLog(@"%@", filePath);
    if([fileManager fileExistsAtPath:filePath]){
        NSLog(@"存在");
        return YES;
    }else{
        return NO;
    }
}

// 返回item数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

// 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ImageCell *cell = (ImageCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.imgView.image = _dataSource[indexPath.row];
    return cell;
}

- (NSMutableArray *)dataSource {
    if (_dataSource == nil) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

// 从缓存中取出指定图片
- (UIImage *)getImgFromCache:(NSInteger) index{
    // 获取cache路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];

    // 文件操作
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"img%ld.png",(long)index]];

    if ([fileManager fileExistsAtPath:filePath]){
        return [UIImage imageWithContentsOfFile:filePath];
    }else {
        return nil;
    }
}



@end
